#!/usr/bin/python3

import _thread
import threading
import random
import time

from time import sleep,ctime

loops = [4,2]
def loop(nloop,nsec,lock):
	print('start loop',nloop,'at:', ctime())
	sleep(nsec)
	print('done loop',nloop,'at:', ctime())
	lock.release()
	
def f1():
	print('start at:',ctime())
	locks = []
	nloops = range(len(loops))
	
	for i in nloops:
		lock = _thread.allocate_lock()
		lock.acquire()
		locks.append(lock)
		
	for i in nloops:
		_thread.start_new_thread(loop,(i,loops[i],locks[i]))
		
	for i in nloops:
		while locks[i].locked():
			pass

def threadFunc():
	for i in range(5):
			print('threadFunc:',i)
			sleep(random.randrange(0,2))

def fib(i):
	if i==0 or i == 1:
		return i
	else:
		return fib(i-1) + fib(i-2)
	
class MyThread(threading.Thread):
	def __init__(self,name):
		threading.Thread.__init__(self,name=name)
		
	def run(self):
		print('multiple start:',ctime())
		for i in range(3):
			print('in thread:',fib(40))
		print('multiple end:',ctime())
		
def t1():
	print('single start:',ctime())
	for i in range(3):
		print('run:',fib(40))
	print('single end:',ctime())
	
	t1 = MyThread('t1')
	t2 = threading.Thread(target=fib)
	#print t1.getName(),t1.isDaemon()
	#t1.setDaemon(True)
	t1.start()
	#t2.start()
	
	t1.join()
	#t2.join()

def routine():
	print('thread name: %s, thread id: %d' %(threading.current_thread().name, threading.get_ident()))
def t2():
	for i in range(3):
		t = threading.Thread(target=routine, args=())
		t.start()

class ThreadJoin():
	def doWaiting():  
		print('start waiting1: ' + time.strftime('%H:%M:%S') + "\n")
		time.sleep(3)  
		print('stop waiting1: ' + time.strftime('%H:%M:%S') + "\n")
	def doWaiting1():  
		print('start waiting2: ' + time.strftime('%H:%M:%S') + "\n")
		time.sleep(8)  
		print('stop waiting2: ', time.strftime('%H:%M:%S') + "\n")

	def run(self):
		tsk = []    
		thread1 = threading.Thread(target = self.doWaiting)  
		thread1.start()  
		tsk.append(thread1)
		thread2 = threading.Thread(target = self.doWaiting1)  
		thread2.start()  
		tsk.append(thread2)
		print('start join: ' + time.strftime('%H:%M:%S') + "\n")
		for tt in tsk:
			tt.join()

if __name__ == '__main__':
	ThreadJoin tj()

	#t2()
	#print('main exit')